package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.log.Log;
import cn.stylefeng.guns.modular.business.comment.FileConfig;
import cn.stylefeng.guns.modular.business.comment.MediaTypeConstant;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.SubBookInfo;
import cn.stylefeng.guns.modular.business.entity.SubFileInfo;
import cn.stylefeng.guns.modular.business.enums.SubFileInfoExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.SubFileInfoMapper;
import cn.stylefeng.guns.modular.business.pojo.SubBookInfoRequest;
import cn.stylefeng.guns.modular.business.pojo.SubFileInfoRequest;
import cn.stylefeng.guns.modular.business.service.SubBookInfoService;
import cn.stylefeng.guns.modular.business.service.SubFileInfoService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.file.api.FileInfoApi;
import cn.stylefeng.roses.kernel.file.api.FileOperatorApi;
import cn.stylefeng.roses.kernel.file.api.enums.FileLocationEnum;
import cn.stylefeng.roses.kernel.file.api.expander.FileConfigExpander;
import cn.stylefeng.roses.kernel.file.api.util.DownloadUtil;
import cn.stylefeng.roses.kernel.rule.constants.SymbolConstant;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现层
 *
 * @author zhangyaowen
 * @date 2021/08/19 16:49
 */
@Service
public class SubFileInfoServiceImpl extends ServiceImpl<SubFileInfoMapper, SubFileInfo> implements SubFileInfoService {

    private static final Log log = Log.get();

    @Resource
    private FileInfoApi fileInfo;
    @Resource
    private FileOperatorApi fileOperator;
    @Resource
    private SubBookInfoService subBookInfoService;
    @Resource
    private FileOperatorApi fileOperatorApi;

	@Override
    public void add(SubFileInfoRequest subFileInfoRequest) {
        SubFileInfo subFileInfo = new SubFileInfo();
        BeanUtil.copyProperties(subFileInfoRequest, subFileInfo);
        this.save(subFileInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(SubFileInfoRequest subFileInfoRequest) {

        // 查询文件的信息
        SubFileInfo subFileInfo = this.getById(subFileInfoRequest.getId());

        // 删除文件记录
        this.removeById(subFileInfoRequest.getId());

        // 删除具体文件
        this.fileOperator.deleteFile(subFileInfo.getFileBucket(), subFileInfo.getFileObjectName());
    }

    @Override
    public void edit(SubFileInfoRequest subFileInfoRequest) {
        SubFileInfo subFileInfo = this.querySubFileInfo(subFileInfoRequest);
        BeanUtil.copyProperties(subFileInfoRequest, subFileInfo);
        this.updateById(subFileInfo);
    }

    @Override
    public SubFileInfo detail(SubFileInfoRequest subFileInfoRequest) {
        return this.querySubFileInfo(subFileInfoRequest);
    }

    @Override
    public PageResult<SubFileInfo> findPage(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        String fileOriginName = subFileInfoRequest.getFileOriginName();
        Long fileType = subFileInfoRequest.getFileType();

        queryWrapper.like(ObjectUtil.isNotEmpty(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);

        Page<SubFileInfo> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }
    @Override
    public PageResult<SubFileInfo> findPageOne(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        String fileOriginName = subFileInfoRequest.getFileOriginName();
        Long fileType = subFileInfoRequest.getFileType();

        queryWrapper.eq(ObjectUtil.isNotEmpty(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);

        Page<SubFileInfo> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }
    @Override
    public PageResult<SubFileInfo> findPageById(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        Long id = subFileInfoRequest.getId();
        Long fileType = subFileInfoRequest.getFileType();

        queryWrapper.like(ObjectUtil.isNotEmpty(id), SubFileInfo::getId, id);
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);

        Page<SubFileInfo> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }

    @Override
    public List<SubFileInfo> findIndexId(SubFileInfoRequest subFileInfoRequest) {
        //LambdaQueryWrapper<SubFileInfo> wrapper = createWrapper(subFileInfoRequest);
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();


        String fileOriginName = subFileInfoRequest.getFileOriginName();
        String fileFirstBelong = subFileInfoRequest.getFileFirstBelong();
        Long fileType = subFileInfoRequest.getFileType();

        queryWrapper.eq(ObjectUtil.isNotEmpty(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
        queryWrapper.eq(ObjectUtil.isNotEmpty(fileFirstBelong), SubFileInfo::getFileFirstBelong, fileFirstBelong);
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);

        return this.list(queryWrapper);
    }

    @Override
    public List<SubFileInfo> findList(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long fileType = subFileInfoRequest.getFileType();
        String fileSecondBelong = subFileInfoRequest.getFileSecondBelong();
        String fileFirstBelong = subFileInfoRequest.getFileFirstBelong();

        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);
        queryWrapper.eq(ObjectUtil.isNotNull(fileSecondBelong), SubFileInfo::getFileSecondBelong, fileSecondBelong);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileFirstBelong), SubFileInfo::getFileFirstBelong, fileFirstBelong);
        return this.list(queryWrapper);

    }
    @Override
    public List<SubFileInfo> findListByName(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long fileType = subFileInfoRequest.getFileType();
        String fileOriginName = subFileInfoRequest.getFileOriginName();
       // String fileFirstBelong = subFileInfoRequest.getFileFirstBelong();

        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);
        queryWrapper.eq(ObjectUtil.isNotNull(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
      //  queryWrapper.like(ObjectUtil.isNotEmpty(fileFirstBelong), SubFileInfo::getFileFirstBelong, fileFirstBelong);
        return this.list(queryWrapper);

    }

    @Override
    public List<SubFileInfo> findAllList(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        String fileOriginName = subFileInfoRequest.getFileOriginName();
        Long fileType = subFileInfoRequest.getFileType();
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
        return this.list(queryWrapper);
    }

    @Override
    public List<Map<String,Object>> findAllInfo(String[] types, String name) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ObjectUtil.isNotEmpty(name), SubFileInfo::getFileOriginName, name);
        queryWrapper.and(wrapper -> {
            for(int i=0 ;i<types.length;i++){
                Long type = Long.parseLong(types[i]);
                wrapper.eq(ObjectUtil.isNotEmpty(type), SubFileInfo::getFileType, type).or();
            }
        });
//        queryWrapper.ne(SubFileInfo::getFileFirstBelong, YunHeKey.UN);
        List<SubFileInfo> list = this.list(queryWrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(SubFileInfo subFileInfo :list) {
            Map<String, Object> map = new HashMap<String, Object>();
//            Map<String, Object> map1 = new HashMap<String, Object>();
//            map = JSONObject.parseObject(JSONObject.toJSONString(eventsInfo), Map.class);

            map.put("title", subFileInfo.getFileOriginName());
            map.put("historyDating","");
            map.put("theCommon","");
            map.put("from",subFileInfo.getFileFirstBelong() );
            map.put("createTime", DateUtil.format(subFileInfo.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",subFileInfo.getFileType() );
            if(subFileInfo.getFileType() == 2){
                SubFileInfoRequest subFileInfoRequest = new SubFileInfoRequest();
                subFileInfoRequest.setFileType(1L);
                subFileInfoRequest.setFileOriginName(map.get("title").toString());
                subFileInfoRequest.setFileFirstBelong(YunHeKey.YUEDU);
                List<SubFileInfo> subFileInfoPageResult = findIndexId(subFileInfoRequest);
                if(!subFileInfoPageResult.isEmpty()) {
                    map.put("fileId", subFileInfoPageResult.get(0).getId());
                }
                SubBookInfoRequest subBookInfoRequest = new SubBookInfoRequest();
                subBookInfoRequest.setBookName(map.get("title").toString());
                List<SubBookInfo> list1 =  subBookInfoService.findList(subBookInfoRequest);
                byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
                SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

                String jmid = YunHeKey.YHYD+list1.get(0).getId();
                String encryptHex = aes.encryptHex(jmid);
                map.put("id",encryptHex);
            }else if(subFileInfo.getFileType() == 3) {
                map.put("id",subFileInfo.getFileSecondBelong());
            }else{
                map.put("id",subFileInfo.getId());
            }

            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public PageResult<SubFileInfo> findImage(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        String fileOriginName = subFileInfoRequest.getFileOriginName();
        Long fileType = subFileInfoRequest.getFileType();
        String fileFirstBelong = "图库";
        queryWrapper.like(ObjectUtil.isNotEmpty(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType)
        .eq(ObjectUtil.isNotNull(fileFirstBelong), SubFileInfo::getFileFirstBelong, fileFirstBelong);

        Page<SubFileInfo> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/08/19 16:49
     */
    private SubFileInfo querySubFileInfo(SubFileInfoRequest subFileInfoRequest) {
        SubFileInfo subFileInfo = this.getById(subFileInfoRequest.getId());
        if (ObjectUtil.isEmpty(subFileInfo)) {
            throw new ServiceException(SubFileInfoExceptionEnum.SUBFILEINFO_NOT_EXISTED);
        }
        return subFileInfo;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/19 16:49
     */
    private LambdaQueryWrapper<SubFileInfo> createWrapper(SubFileInfoRequest subFileInfoRequest) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long id = subFileInfoRequest.getId();
        Integer fileLocation = subFileInfoRequest.getFileLocation();
        String fileBucket = subFileInfoRequest.getFileBucket();
        String fileOriginName = subFileInfoRequest.getFileOriginName();
        String fileSuffix = subFileInfoRequest.getFileSuffix();
        Long fileSizeKb = subFileInfoRequest.getFileSizeKb();
        String fileSizeInfo = subFileInfoRequest.getFileSizeInfo();
        String fileObjectName = subFileInfoRequest.getFileObjectName();
        Long fileType = subFileInfoRequest.getFileType();
        String filePath = subFileInfoRequest.getFilePath();

        queryWrapper.eq(ObjectUtil.isNotNull(id), SubFileInfo::getId, id);
        queryWrapper.eq(ObjectUtil.isNotNull(fileLocation), SubFileInfo::getFileLocation, fileLocation);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileBucket), SubFileInfo::getFileBucket, fileBucket);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileOriginName), SubFileInfo::getFileOriginName, fileOriginName);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileSuffix), SubFileInfo::getFileSuffix, fileSuffix);
        queryWrapper.eq(ObjectUtil.isNotNull(fileSizeKb), SubFileInfo::getFileSizeKb, fileSizeKb);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileSizeInfo), SubFileInfo::getFileSizeInfo, fileSizeInfo);
        queryWrapper.like(ObjectUtil.isNotEmpty(fileObjectName), SubFileInfo::getFileObjectName, fileObjectName);
        queryWrapper.eq(ObjectUtil.isNotNull(fileType), SubFileInfo::getFileType, fileType);
        queryWrapper.like(ObjectUtil.isNotEmpty(filePath), SubFileInfo::getFilePath, filePath);

        return queryWrapper;
    }
    @Override
    public Long uploadFile(MultipartFile file){

        // 生成文件的唯一id
        Long fileId = IdWorker.getId();

        // 获取文件原始名称
        String originalFilename = file.getOriginalFilename();

        // 获取文件后缀
        String fileSuffix = null;
        Long fileType = null;
        if (ObjectUtil.isNotEmpty(originalFilename)) {
            fileSuffix = StrUtil.subAfter(originalFilename, SymbolConstant.DOT, true);
            if(this.isPic(fileSuffix)){
                fileType = 1L;//图片
            }
            if(this.isFile(fileSuffix)){
                fileType = 2L;//文件
            }
            if(this.isAudio(fileSuffix)){
                fileType = 3L;//音视频
            }
            if(this.isVideo(fileSuffix)){
                fileType = 4L;//视频
            }
        }
        String fileAllName = StrUtil.removeSuffix(originalFilename, "."+fileSuffix);

                    String [] strings =StrUtil.splitToArray(fileAllName, "-");
        String fileOriginal =null;
        String secondBelong =null;
        String firstBelong =null;
        if (strings[0] != null || strings[0] != "") {
            fileOriginal = strings[0];
        }
        if(strings.length >1 && strings.length <=2) {
            if (strings[1] != null || strings[1] != "") {
                firstBelong = strings[1];
            }
        }
        if(strings.length >2) {
            if (strings[1] != null || strings[1] != "") {
                secondBelong = strings[1];
            }
            if (strings[2] != null || strings[2] != "") {
                firstBelong = strings[2];
            }
        }
        // 生成文件的最终名称
        String finalName = fileId + SymbolConstant.DOT + fileSuffix;

        // 存储文件
        byte[] bytes;
        try {
            bytes = file.getBytes();
            fileOperator.storageFile(FileConfig.SUB_BUCKET, finalName, bytes); //本地服务器存储
        } catch (IOException e) {
            throw new ServiceException(SubFileInfoExceptionEnum.ERROR_FILE);
        }

        // 计算文件大小kb
        long fileSizeKb = Convert.toLong(NumberUtil.div(new BigDecimal(file.getSize()), BigDecimal.valueOf(1024))
                .setScale(0, BigDecimal.ROUND_HALF_UP));

        //计算文件大小信息
        String fileSizeInfo = FileUtil.readableFileSize(file.getSize());

        // 存储文件信息
        SubFileInfo subFileInfo = new SubFileInfo();
        subFileInfo.setId(fileId);
        subFileInfo.setFileLocation(FileLocationEnum.LOCAL.getCode());
        subFileInfo.setFileBucket(FileConfig.SUB_BUCKET);
        subFileInfo.setFileObjectName(finalName);
        subFileInfo.setFileOriginName(fileOriginal);
        subFileInfo.setFileSuffix(fileSuffix);
        subFileInfo.setFileSizeKb(fileSizeKb);
        subFileInfo.setFileSizeInfo(fileSizeInfo);
        subFileInfo.setFileFirstBelong(firstBelong);
        subFileInfo.setFileSecondBelong(secondBelong);
        subFileInfo.setFileType(fileType);
        subFileInfo.setFilePath(FileConfigExpander.getLocalFileSavePathWindows());
        this.save(subFileInfo);
        if(isPic(subFileInfo.getFileSuffix())){
            String rarFile = subFileInfo.getFilePath()+"/"+ FileConfig.SUB_BUCKET+"/"+fileId+".jpg";
            ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(bytes);
            File file1 = new File(rarFile);
            Img.from(byteArrayInputStream)
                    .setQuality(0.5)
                    .scale(0.4f)
                    .write(file1);

        }
        // 返回文件id
        return fileId;
    }

    @Override
    public SubFileInfoRequest getFileInfoResult(Long fileId) {
        byte[] fileBytes;
        // 获取文件名
        SubFileInfo subFileInfo = this.getById(fileId);
        if (subFileInfo == null) {
            throw new ServiceException(SubFileInfoExceptionEnum.NOT_EXISTED_FILE);
        }
        try {
            // 返回文件字节码
            fileBytes = fileOperator.getFileBytes(FileConfig.SUB_BUCKET, subFileInfo.getFileObjectName());
        } catch (Exception e) {
            log.error(">>> 获取文件流异常，请求号为：{}，具体信息为：{}",  e.getMessage());
            throw new ServiceException(SubFileInfoExceptionEnum.FILE_STREAM_ERROR);
        }

        SubFileInfoRequest sysFileInfoResult = new SubFileInfoRequest();
        BeanUtil.copyProperties(subFileInfo, sysFileInfoResult);
        sysFileInfoResult.setFileBytes(fileBytes);

        return sysFileInfoResult;
    }

    @Override
    public void assertFile(Long field) {
        SubFileInfo subFileInfo = this.getById(field);
        if (ObjectUtil.isEmpty(subFileInfo)) {
            throw new ServiceException(SubFileInfoExceptionEnum.NOT_EXISTED);
        }
    }

    @Override
    public void preview(SubFileInfoRequest subFileInfoRequest, HttpServletResponse response) {

        byte[] fileBytes;
        //根据文件id获取文件信息结果集
        SubFileInfoRequest subFileInfoRequest1 = this.getFileInfoResult(subFileInfoRequest.getId());
        //获取文件后缀
        String fileSuffix = subFileInfoRequest1.getFileSuffix().toLowerCase();
        //获取文件字节码
        fileBytes = subFileInfoRequest1.getFileBytes();

        String path = subFileInfoRequest1.getFilePath();
        String pathname = subFileInfoRequest1.getFileBucket();
        String idname =subFileInfoRequest1.getId().toString();
        //如果是图片类型，则直接输出
        if (this.isPic(fileSuffix)) {
            try {
                //设置contentType
                response.setContentType("image/jpeg");
                //获取outputStream
                ServletOutputStream outputStream = response.getOutputStream();
                //输出
                IoUtil.write(outputStream, true, fileBytes);
            } catch (IOException e) {
                throw new ServiceException(SubFileInfoExceptionEnum.PREVIEW_ERROR_NOT_SUPPORT);
            }

        }
        if (this.isFile(fileSuffix)) {
            try {
                //设置contentType
                response.setContentType("application/pdf");
                //获取outputStream
                ServletOutputStream outputStream = response.getOutputStream();

//                File file=new File(path+"/"+pathname+"/"+idname+"."+fileSuffix);
//                byte[] b = new byte[512];
//                FileInputStream in=null;
//                    in= new FileInputStream(file);
//                    while ((in.read(b))!=-1) {
//                        outputStream.write(b);
//                    }
//                    in.close();
                //输出
                IoUtil.write(outputStream, true, fileBytes);

            } catch (IOException e) {
                throw new ServiceException(SubFileInfoExceptionEnum.PREVIEW_ERROR_NOT_SUPPORT);
            }
        }
        if (this.isVideo(fileSuffix)) {
            try {
                //设置contentType0
                response.setContentType("video/mpeg4");
                //获取outputStream
                ServletOutputStream outputStream = response.getOutputStream();

                //输出
                IoUtil.write(outputStream, true, fileBytes);
            } catch (IOException e) {
                throw new ServiceException(SubFileInfoExceptionEnum.PREVIEW_ERROR_NOT_SUPPORT);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (this.isAudio(fileSuffix)) {
            try {


                response.addHeader("Accept-Ranges", "bytes");
                response.addHeader("Content-Length", fileBytes.length + "");
                response.addHeader("Content-Range", "bytes " + 0 + "-");// + (fileBytes.length - 1) + "/" + fileBytes.length);
                //response.addHeader("Content-Type", "audio/mpeg;charset=UTF-8");

                //设置contentType
                response.setContentType("audio/mp3");
                //获取outputStream
                ServletOutputStream outputStream = response.getOutputStream();

                //输出
                IoUtil.write(outputStream, true, fileBytes);
                fileBytes = null;
            } catch (IOException e) {
                throw new ServiceException(SubFileInfoExceptionEnum.PREVIEW_ERROR_NOT_SUPPORT);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void rarPreview(SubFileInfoRequest subFileInfoRequest, HttpServletResponse response) {

          String fileUrl= "D:/tmp/rarBucket/"+subFileInfoRequest.getId()+".jpg";

          BufferedInputStream in = FileUtil.getInputStream(fileUrl);

            try {
                //设置contentType
                response.setContentType("image/jpeg");
                //获取outputStream
                ServletOutputStream outputStream = response.getOutputStream();

                IoUtil.read(in).writeTo(outputStream);

            } catch (IOException e) {
                throw new ServiceException(SubFileInfoExceptionEnum.PREVIEW_ERROR_NOT_SUPPORT);
            }
    }

    @Override
    public void download(SubFileInfoRequest subFileInfoRequest, HttpServletResponse response) {
        // 获取文件信息结果集
        SubFileInfoRequest fileInfoResult = this.getFileInfoResult(subFileInfoRequest.getId());
        String fileName = fileInfoResult.getFileOriginName();
        byte[] fileBytes = fileInfoResult.getFileBytes();
        DownloadUtil.download(fileName, fileBytes, response);
    }

    /**
     * 获取文件信息表
     *
     * @author stylefeng
     * @date 2020/6/7 22:15
     */
    private SubFileInfo querySysFileInfo(SubFileInfoRequest subFileInfoRequest) {
        SubFileInfo subFileInfo = this.getById(subFileInfoRequest.getId());
        if (ObjectUtil.isEmpty(subFileInfo)) {
            throw new ServiceException(SubFileInfoExceptionEnum.NOT_EXISTED);
        }
        return subFileInfo;
    }


    /**
     * 根据文件后缀判断是否图片
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isPic(String fileSuffix) {
        return MediaTypeConstant.IMG_JPG.equals(fileSuffix)
                || MediaTypeConstant.IMG_JPEG.equals(fileSuffix)
                || MediaTypeConstant.IMG_PNG.equals(fileSuffix)
                || MediaTypeConstant.IMG_GIF.equals(fileSuffix)
                || MediaTypeConstant.IMG_TIF.equals(fileSuffix)
                || MediaTypeConstant.IMG_BMP.equals(fileSuffix);
    }
    /**
     * 根据文件后缀判断是否文件
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isFile(String fileSuffix) {
        return MediaTypeConstant.FILE_DOC.equals(fileSuffix)
                || MediaTypeConstant.FILE_CSV.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOCM.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOCX.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOTM.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOT.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOTX.equals(fileSuffix)
                || MediaTypeConstant.FILE_ET.equals(fileSuffix)
                || MediaTypeConstant.FILE_HTML.equals(fileSuffix)
                || MediaTypeConstant.FILE_PDF.equals(fileSuffix)
                || MediaTypeConstant.FILE_TXT.equals(fileSuffix)
                || MediaTypeConstant.FILE_WPS.equals(fileSuffix)
                || MediaTypeConstant.FILE_WPT.equals(fileSuffix)
                || MediaTypeConstant.FILE_XLS.equals(fileSuffix)
                || MediaTypeConstant.FILE_XLSX.equals(fileSuffix)
                || MediaTypeConstant.FILE_XLT.equals(fileSuffix);
    }
    /**
     * 根据文件后缀判断是否视频
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isVideo(String fileSuffix) {
        return MediaTypeConstant.VIDEO_AVI.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_FLV.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MKV.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MOV.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MPEG.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MP4.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MPG.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_RM.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_RMVB.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_WMV.equals(fileSuffix);
    }
    /**
     * 根据文件后缀判断是否音频
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isAudio(String fileSuffix) {
        return MediaTypeConstant.VIDEO_WAVE.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MP3.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_WMA.equals(fileSuffix);
    }

    public static String getcontentTypes(String fileSuffix) {
        if (fileSuffix.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (fileSuffix.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (fileSuffix.equalsIgnoreCase("pdf")) {
            return "application/pdf";
        }
        if (fileSuffix.equalsIgnoreCase("jpeg") || fileSuffix.equalsIgnoreCase("jpg")
                || fileSuffix.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (fileSuffix.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (fileSuffix.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (fileSuffix.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (fileSuffix.equalsIgnoreCase("pptx") || fileSuffix.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (fileSuffix.equalsIgnoreCase("docx") || fileSuffix.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (fileSuffix.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }


    @Override
    public List<Map<String,Object>> assFileByValue(String value ,String fileType) {
        LambdaQueryWrapper<SubFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ObjectUtil.isNotEmpty(value), SubFileInfo::getFileOriginName, value);
        boolean type = StrUtil.contains(fileType,";");
        if(type) {
//            String[] types = StrUtil.split(fileType, ";").toArray(new String[0]);
            String [] types =  StrUtil.splitToArray(fileType, ";");
            queryWrapper.and(i-> i.eq(ObjectUtil.isNotEmpty( types[0]), SubFileInfo::getFileType, types[0]).or()
                    .eq(ObjectUtil.isNotEmpty( types[1]), SubFileInfo::getFileType, types[1]).or());
            queryWrapper.eq(SubFileInfo::getFileFirstBelong, YunHeKey.KECHENG);
            queryWrapper.eq(SubFileInfo::getFileFirstBelong, "课程");
        }else {
            queryWrapper.eq(ObjectUtil.isNotEmpty(fileType), SubFileInfo::getFileType, fileType);
        }

        if("1".equals(fileType)) {
            queryWrapper.ne(SubFileInfo::getFileFirstBelong, "UN");
            queryWrapper.ne(SubFileInfo::getFileFirstBelong, "课程");
            queryWrapper.ne(SubFileInfo::getFileFirstBelong, "阅读");
            queryWrapper.ne(SubFileInfo::getFileFirstBelong, "资讯");
        }



        List<SubFileInfo> list = this.list(queryWrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(SubFileInfo subFileInfo :list) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("title", subFileInfo.getFileOriginName());
            map.put("historyDating","");
            map.put("theCommon","");
            map.put("from",subFileInfo.getFileFirstBelong() );
            map.put("createTime", DateUtil.format(subFileInfo.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",subFileInfo.getFileType() );
            map.put("id",subFileInfo.getId());

            mapList.add(map);
        }
        if(mapList.size() >= 4 ){
            List<Map<String,Object>> mapList1 = new ArrayList<>();
            mapList1 = CollectionUtil.sub(mapList,0,4);
            return mapList1;
        }else{
            int limit  = 4 - mapList.size();

            LambdaQueryWrapper<SubFileInfo> wrapper = new LambdaQueryWrapper<>();

            if(type) {
                String[] types = StrUtil.splitToArray(fileType, ";");
                wrapper.and(i-> i.eq(ObjectUtil.isNotEmpty( types[0]), SubFileInfo::getFileType, types[0]).or()
                        .eq(ObjectUtil.isNotEmpty( types[1]), SubFileInfo::getFileType, types[1]).or());
                wrapper.eq(SubFileInfo::getFileFirstBelong, YunHeKey.KECHENG);
            }else {
                wrapper.eq(ObjectUtil.isNotEmpty(fileType), SubFileInfo::getFileType, fileType);
            }
            if("1".equals(fileType)) {
                wrapper.ne(SubFileInfo::getFileFirstBelong, "UN");
                wrapper.ne(SubFileInfo::getFileFirstBelong, "课程");
                wrapper.ne(SubFileInfo::getFileFirstBelong, "阅读");
                wrapper.ne(SubFileInfo::getFileFirstBelong, "资讯");
            }
            List<SubFileInfo> listNum =  this.list(wrapper);
            if(listNum.size()<4){
                return mapList;
            }else {

                int[] roms=new int[5];
                boolean tt = true;
                List<SubFileInfo> list1 = new ArrayList<>();
                for(int i= 0; i<limit;i++){
                    int num = RandomUtil.randomInt(0, listNum.size())+1;

                    for(int j=0;j<roms.length;j++){
                        if( num == roms[j]){
                            tt = false;
                            break;
                        }
                    }
                    if(tt) {
                        roms[i] = num;
                        list1.add(listNum.get(num-1));

                    }else{
                        --i;
                        continue;
                    }
                }

                for (SubFileInfo subFileInfo : list1) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    if(type) {
                        SubFileInfoRequest subFileInfoRequest = new SubFileInfoRequest();
                        subFileInfoRequest.setFileType(1L);
                        subFileInfoRequest.setFileOriginName(subFileInfo.getFileSecondBelong());
                        subFileInfoRequest.setFileFirstBelong(YunHeKey.KECHENG);
                        List<SubFileInfo> subFileInfoPageResult = this.findIndexId(subFileInfoRequest);
                        if (!subFileInfoPageResult.isEmpty()) {
                            map.put("imgId", subFileInfoPageResult.get(0).getId());
                        }
                    }

                    map.put("className",subFileInfo.getFileSecondBelong());
                    map.put("title", subFileInfo.getFileOriginName());
                    map.put("historyDating", "");
                    map.put("theCommon", "");
                    map.put("from", subFileInfo.getFileFirstBelong());
                    map.put("createTime", DateUtil.format(subFileInfo.getCreateTime(), "yyyy-MM-dd"));
                    map.put("type", subFileInfo.getFileType());
                    map.put("id", subFileInfo.getId());

                    mapList.add(map);
                }
                return mapList;
            }
        }

    }

}